package com.zhuoyue.web.controller.system;

import com.zhuoyue.common.annotation.Log;
import com.zhuoyue.common.core.controller.BaseController;
import com.zhuoyue.common.core.domain.AjaxResult;
import com.zhuoyue.common.core.domain.entity.SysUser;
import com.zhuoyue.common.core.page.TableDataInfo;
import com.zhuoyue.common.enums.BusinessType;
import com.zhuoyue.common.utils.DealLogUtils;
import com.zhuoyue.common.utils.StringUtils;
import com.zhuoyue.common.utils.poi.ExcelUtil;
import com.zhuoyue.system.domain.dto.GatewayProReqDTO;
import com.zhuoyue.system.domain.po.TblGatewayPo;
import com.zhuoyue.system.domain.vo.TblGatewayVo;
import com.zhuoyue.system.mapper.TblGatewayLogMapper;
import com.zhuoyue.system.mapper.TblGatewayMapper;
import com.zhuoyue.system.mapper.TblHomeMapper;
import com.zhuoyue.system.service.ITblGatewayService;
import com.zhuoyue.web.utils.OrgCodeUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotBlank;
import java.text.MessageFormat;
import java.util.List;


/**
 * 网关Controller
 *
 * @author hewenze
 * @date 2020-08-07
 */
@RestController
@Api(value = "网关接口", tags = "网关接口")
@RequestMapping("/system/gateway")
public class TblGatewayController extends BaseController {
    @Autowired
    private ITblGatewayService tblGatewayService;

    @Autowired
    private TblGatewayMapper tblGatewayMapper;

    @Autowired
    private TblGatewayLogMapper tblGatewayLogMapper;

    @Autowired
    private TblHomeMapper tblHomeMapper;

    @Autowired
    private OrgCodeUtils orgCodeUtils;

    @Autowired
    private DealLogUtils dealLogUtils;

    /**
     * 查询网关列表
     */
    @GetMapping("/list")
    @ApiOperation(value = "查询网关列表", notes = "查询网关列表")
    public TableDataInfo list(GatewayProReqDTO gatewayProReq, HttpServletRequest request) {

        TblGatewayPo tblGatewayPo = new TblGatewayPo().dtoToDo(gatewayProReq);
        startPage();
        List<TblGatewayVo> list = tblGatewayService.selectTblGatewayList(tblGatewayPo);
        return getDataTable(list);
    }

    /**
     * 查询网关详细信息
     */
    @GetMapping
    @ApiOperation(value = "获取网关详情信息", notes = "网关详情信息")
    public AjaxResult getById(String id, String gatewayMac) {
        if (StringUtils.isNotEmpty(id)) {
            return AjaxResult.success(tblGatewayService.selectById(id));
        } else {
            if (StringUtils.isEmpty(gatewayMac)) {
                return AjaxResult.error("参数错误");
            }
            return AjaxResult.success(tblGatewayService.selectByMac(gatewayMac));
        }
    }


    /**
     * 解绑家庭
     */
    @PutMapping("/untie/{id}")
    @ApiOperation(value = "查询网关列表", notes = "查询网关列表")
    @Log(title = "解绑网关", businessType = BusinessType.UPDATE)
    public AjaxResult untieHome(@PathVariable("id") String id, HttpServletRequest request) {
        String classAndMethodName = this.getClass().getName() + "." + "untieHome()";
        SysUser user = orgCodeUtils.getLoginUser(request).getUser();
        //修改前的数据
        TblGatewayVo tblGatewayVos1 = tblGatewayMapper.selectGatewayVoById(id);
        int i = tblGatewayService.untieTblGatewayById(id);
        if (i < 1) {
            return AjaxResult.error("解绑失败");
        }
        //修改后的数据
        TblGatewayVo tblGatewayVos2 = tblGatewayMapper.selectGatewayVoById(id);
        dealLogUtils.setRedisSourceAndTargetData(classAndMethodName, user, tblGatewayVos1, tblGatewayVos2);
        return AjaxResult.success("解绑成功");
    }

    /**
     * 导出网关列表
     */
    @ApiOperation(value = "导出设备列表", notes = "导出设备列表")
    @Log(title = "网关", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(TblGatewayPo tblGatewayPo, HttpServletRequest request) {

        tblGatewayPo.setOrganizationCode(orgCodeUtils.getOrgCode(request));
        tblGatewayPo.setPageNum(null);
        tblGatewayPo.setPageSize(null);
        List<TblGatewayVo> list = tblGatewayService.selectTblGatewayList(tblGatewayPo);
        System.out.println("list" + list.size());
        ExcelUtil<TblGatewayVo> util = new ExcelUtil<TblGatewayVo>(TblGatewayVo.class);
        return util.exportExcel(list, "网关");
    }

    @GetMapping("/listByHomeId")
    public TableDataInfo listByHomeId(String homeId) {
        return getDataTable(tblGatewayMapper.selectGatewayByHomeId(homeId));
    }

    @GetMapping("send/cmd")
    public AjaxResult sendCmd(@NotBlank String cmd, @NotBlank String gatewayMac) {
        final int code = 200;

        Object[] objects = new Object[]{StringUtils.deleteWhitespace(cmd), StringUtils.deleteWhitespace(gatewayMac)};
        String cmdUrl = "https://api.zyzncloud.com/api/command/cmdSend?cmd={0}&gatewayMac={1}";
        MessageFormat url = new MessageFormat(cmdUrl);
        String httpUrl = url.format(objects);
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<Object> forEntity = restTemplate.postForEntity(httpUrl, null, Object.class);
        if (code == forEntity.getStatusCode().value()) {
            return AjaxResult.success("发送成功");
        }
        return AjaxResult.error("发送失败");
    }
}
